package controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import util.CommonConstant;
import util.CommonSendRequestUtil;
import util.KKResponse;
import com.alibaba.fastjson.JSONObject;

@Controller
public class LoginController {
	/**
	 * pageLogin(跳转到登陆页面)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *ModelAndView
	 * @exception
	 * @since  1.0.0
	*/
	@RequestMapping ("/pageLogin")  
    public ModelAndView pageLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{  
       ModelAndView modelAndView = new ModelAndView();  
       modelAndView.setViewName( "login.jsp" );  
       return modelAndView;  
    } 
	
	/**
	 * login(登录)
	 * (这里描述这个方法适用条件 – 可选)
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *ModelAndView
	 * @exception
	 * @since  1.0.0
	*/
	@RequestMapping ("/login")  
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws Exception{  
		//1.获取用户登录信息
		String user = request.getParameter("user");
		String postUrl = CommonConstant.baseUrl +"/user/login";
		JSONObject obj = JSONObject.parseObject(user);
	    //2.发送用户信息
		KKResponse resp = CommonSendRequestUtil.sendRestPostWithoutTokenRequest(postUrl, obj);
		JSONObject responseBody = JSONObject.parseObject(resp.getResponseBody());
		String token = responseBody.getString("result");
		//3.获取到session信息
		HttpSession session = request.getSession(); 
		session.setAttribute("token", token);
		//4.返回结果
		PrintWriter out = response.getWriter();
		out.print(responseBody);
		out.flush();
		out.close();
		return null; 
    } 
	
}
